<?php

declare(strict_types=1);

namespace App\Service;

use App\Library\Common;
use Hyperf\Di\Annotation\Inject;
use phpDocumentor\Reflection\Types\Integer;

class OrderDeliveryService
{

    /**
     * 固定费用
     */
    const RULE_TYPE_FIXED = 1;
    const RULE_TYPE_PIECE = 2; // 按键
    const RULE_TYPE_WEIGHT = 3;// 按重量
    const RULE_TYPE_VOLUME = 4;// 按体积

    /**
     * @Inject
     * @var DeliveryRuleAreaService
     */
    private $deliveryRuleArea;

    /**
     * @Inject
     * @var DeliveryTplService
     */
    private $tpl;

    /**
     * @Inject
     * @var DeliveryRuleService
     */
    private $rule;

    /**
     * 计算订单运费
     * @param array $orderData
     * @param bool $is_commit
     * @param int $delivery_type
     * @return bool
     */
    public function calculatePrice(array &$orderData, bool $is_commit, int $delivery_type): bool
    {
        // 获取收货地址适用的运费模板
        $orderData['pay_order_data']['delivery_price'] = 0;
        // 同城配送
        if ($delivery_type != ShopDeliveryConfigService::TYPE_EXPRESS) {
            foreach ($orderData['shop_order_data'] as &$shop_order) {
                if ($shop_order['delivery_valid']) {
                    foreach ($shop_order['delivery_types'] as $config_type) {
                        // 自提
                        if ($config_type['delivery_type'] == $delivery_type && $delivery_type == ShopDeliveryConfigService::TYPE_OWN) {
                            $shop_order['order_info']['delivery_price'] = 0;
                            break;
                        } elseif ($config_type['delivery_type'] == $delivery_type && $delivery_type == ShopDeliveryConfigService::TYPE_LOCAL) {
                            // 按距离计算配送费
                            $shop_order['order_info']['delivery_price'] = $shop_order['delivery_distance'] <= $config_type['base_range'] ? $config_type['base_price'] :
                                $config_type['base_price'] + ceil($shop_order['delivery_distance'] / $config_type['add_range']) * $config_type['add_price'];
                            break;
                        } else {
                            $shop_order['order_info']['delivery_price'] = 0;//违规
                        }
                    }

                    // 提交操作以单位分计算
                    if ($is_commit) {
                        // 商家运费：提交（分）
                        $shop_order['order_info']['delivery_price'] = Common::yuan2fen(floatval($shop_order['order_info']['delivery_price']));// 转换为分进行计算
                    }
                    // 总订单总运费、总订单金额（分|元）
                    $orderData['pay_order_data']['delivery_price'] += $shop_order['order_info']['delivery_price'];
                    $orderData['pay_order_data']['pay_price'] += $shop_order['order_info']['delivery_price'];
                }
            }
            return true;
        }


        // pay_order_data => ['pay_price','product_price','delivery_price'(总订单运费)]
        // shop_order_data => [ [shop_id,order_info=>[order_price,product_price,delivery_price(店铺订单运费)],product_info=>[[sku_id,product_id,quantity,single_price]]] ]
        // address_info => [address_arr=>[0=>id(省ID)，1=>id(市ID)，2=>id(区ID)]]

        // 获取收货地址适用的运费模板
        $orderData['delivery_price'] = 0;
        // 获取地区适配模板
        foreach ($orderData['shop_order_data'] as &$shop_order) {
            // 店铺运费
            $shop_order['order_info']['delivery_price'] = 0;
            // 运费计价方式
            $rule_type_fields = [self::RULE_TYPE_PIECE => 'quantity', self::RULE_TYPE_WEIGHT => 'weight', self::RULE_TYPE_VOLUME => 'volume'];
            // 用于相同模板数量统计
            $tpl_tmp = [];
            // 合并相同模板商品数量
            foreach ($shop_order['product_info'] as &$p) {
                // 相同模板的商品合并
                if ($p['is_valid'] == 1) {
                    $tpl_tmp[$p['tpl_id']] = isset($tpl_tmp[$p['tpl_id']]) ? $tpl_tmp[$p['tpl_id']] += $p['quantity'] : $p['quantity'];
                }
            }
            $shop_order['order_info']['delivery_price'] = 0;
            $order_free = false;
            // 计算高首费低增费
            $first_price = 0;
            $add_price = 0;
            // 首费增费计算
//            print_r($shop_order['shop_id'] . '-------====');
            foreach ($shop_order['product_info'] as $this_k => &$shop_sku) {
                if ($shop_sku['is_valid'] == 1) {
                    // 获取商品运费模板
                    $tpl = $shop_sku['tpl'];
                    $rule = $shop_sku['rule'];
//                    if ($shop_order['shop_id'] == 118) {
//                        echo "店铺118的运费规则：";
//                    }
                    // 订单高优先级(触发最终订单价格为0)
                    $fixed_free = $tpl['is_all_area'] == 1 ? $tpl['min_price_free'] : $rule['min_price_free'] ?? 0;
                    $fixed_is_free = $tpl['is_all_area'] == 1 ? $tpl['is_free'] : $rule['area_free'] ?? 0;
//                    echo "是否为固定包邮：".$fixed_is_free;
                    // 订单高优先级模式（触发订单金额额为0）
                    if ($tpl['use_type'] == 2 && $tpl['is_use'] == 1) {
                        // 符合订单免邮-不计算运费
                        // 固定包邮
                        if ($fixed_is_free == 1) {
//                            echo "固定包邮-";
                            $shop_order['order_info']['delivery_price'] = 0;
                            $order_free = true;
                            break;
                            // 订单免邮条件：满 *（件、重量、体积）的价格：订单免运费
                        } elseif ($tpl['is_other_free'] == 1) {
//                            echo "订单额外满*钱免邮-";
                            // 订单额外满（金额）免邮
                            if ($shop_order['order_info']['product_price'] >= $fixed_free) {
                                $shop_order['order_info']['delivery_price'] = 0;
                                $order_free = true;
                                break;
                            }
                            // 订单额外满（件、体积、重量）免邮
                            //$set_subtotal = $tpl['rule_type'] == 2 ? $shop_sku['quantity'] : $shop_sku['quantity'] * $shop_sku[$rule_type_fields[$tpl['rule_type']]];
                            $set_subtotal = $shop_sku['quantity'];
                            if ($tpl['other_free_set'] <= $set_subtotal) {
//                                echo "订单额外满*体积免邮-";
                                $shop_order['order_info']['delivery_price'] = 0;
                                $order_free = true;
                                break;
                            } else {
                                //
                                // 商品运费规则
//                                echo "商品单独运费规则-";
                                goto fixed_price;
                            }
                        } else {
                            goto fixed_price;
                        }
                        // 商品运费模板
                    } elseif ($tpl['use_type'] == 1) {
//                        echo "商品运费模板：";
                        // 商品是否免邮
                        if ($fixed_is_free == 1) {
                            $shop_sku['delivery_price'] = 0;
                            $shop_sku['is_free_delivery'] = 1;
                            continue;
                            // 商品是否额外免邮规则(仅按件数判断是否免邮)
                        } elseif ($tpl['is_other_free'] == 1) {
//                            echo "额外免邮：";
                            //$set_subtotal = $tpl['rule_type'] == 2 ? $shop_sku['quantity'] : $shop_sku['quantity'] * $shop_sku[$rule_type_fields[$tpl['rule_type']]];
                            $set_subtotal = $shop_sku['quantity'];
                            if ($tpl['other_free_set'] <= $set_subtotal) {
                                $shop_sku['delivery_price'] = 0;
                                $shop_sku['is_free_delivery'] = 1;
                                continue;
                            } else {
                                // 高首费低增费计算首费、增费
                                goto fixed_price;
                            }
                        } else {
                            fixed_price:
                            // 是否固定运费
                            if ($tpl['rule_type'] == 1) {
//                                echo "固定运费" . $rule['first_price'] . "\r\n";
                                $shop_sku['is_fixed'] = 1;
                                $shop_sku['delivery_price'] = $rule['first_price'];
                            } else {
                                // 高首费低增费计算
//                                echo "高首费低增费";
                                if ($rule['first_price'] >= $first_price) {
                                    // 首费相同取增费
                                    if ($rule['first_price'] == $first_price) {
                                        if ($rule['add_price'] < $add_price) {
                                            $add_price = $rule['add_price'];// 低增费
                                        }
                                    } else {
                                        $first_price = $rule['first_price'];
                                        if (empty($add_price)) {
                                            $add_price = $rule['add_price'];
                                        }
                                    }
                                }
                            }
                        }
                        // 低优先级运费模板
                    } else {
                        // 商品是否免邮
                        if ($fixed_is_free == 1) {
                            $shop_sku['delivery_price'] = 0;
                            $shop_sku['is_free_delivery'] = 1;
                            continue;
                            // 商品是否额外免邮
                        } elseif ($tpl['is_other_free'] == 1) {
                            //$set_subtotal = $tpl['rule_type'] == 2 ? $shop_sku['quantity'] : $shop_sku['quantity'] * $shop_sku[$rule_type_fields[$tpl['rule_type']]];
                            $set_subtotal = $shop_sku['quantity'];
                            if ($fixed_free <= $set_subtotal) {
                                $shop_sku['delivery_price'] = 0;
                                $shop_sku['is_free_delivery'] = 1;
                                continue;
                            } else {
                                // 高首费低增费计算首费、增费
                                goto fixed_price;
                            }
                        } else {
                            // 未设置额外免邮（判断是否符合订单满免规则）
                            $set_subtotal = $tpl['rule_type'] == 2 ? $shop_sku['quantity'] * $shop_sku['single_price'] : $shop_sku['quantity'] * $shop_sku[$rule_type_fields[$tpl['rule_type']]] * $shop_sku['single_price'];
                            if ($fixed_free <= $set_subtotal) {
                                $shop_sku['delivery_price'] = 0;
                                $shop_sku['is_free_delivery'] = 1;
                                continue;
                            }
                            // 是否固定运费
                            if ($tpl['rule_type'] == 1) {
                                $shop_sku['delivery_price'] = $fixed_free;
                                $shop_sku['is_fixed'] = 1;
                                continue;
                            } else {
                                // 高首费低增费计算
                                echo "高首费递增费";
                                goto fixed_price;
                            }
                        }
                    }// 邮费金额计算:固定邮费、商品包邮、订单包邮、获取最高首费最低增费
                } // 有效商品
            } // 订单商品

            if (!$order_free) {
                foreach ($shop_order['product_info'] as $delivery) {
                    if ($delivery['is_valid'] == 0) {
                        continue;
                    }
                    // 计算高首费低增费运费(排除包邮/固定运费)
                    if (empty($delivery['delivery_price']) && empty($delivery['is_free_delivery']) && !isset($delivery['is_fixed'])) {
                        // 有多个商品模板对比的时候（取高首费低增费）：不满足首量按首量取首费
                        if ($tpl_tmp[$delivery['tpl_id']] - $delivery['rule']['first_num'] <= 0) {
                            $delivery['delivery_price'] = $first_price;
                        } else {
                            $delivery['delivery_price'] = $first_price + ceil(($tpl_tmp[$delivery['tpl_id']] - $delivery['rule']['first_num']) / $delivery['rule']['add_num']) * $add_price;
                        }
                    }
                    // 取最大值运费
                    $shop_order['order_info']['delivery_price'] = $shop_order['order_info']['delivery_price'] < $delivery['delivery_price'] ? $delivery['delivery_price'] : $shop_order['order_info']['delivery_price'];
                }
            }
            // 提交操作以单位分计算
            if ($is_commit) {
                // 商家运费：提交（分）
                $shop_order['order_info']['delivery_price'] = Common::yuan2fen(floatval($shop_order['order_info']['delivery_price']));// 转换为分进行计算
            }
            // 总订单总运费、总订单金额（分|元）
            $orderData['pay_order_data']['delivery_price'] += $shop_order['order_info']['delivery_price'];
            $orderData['pay_order_data']['pay_price'] += $shop_order['order_info']['delivery_price'];
        }// shop_delivery end
        return true;
    }
}